import Vue from "vue";
import Router from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";
import adminMenu from "@/assets/menus/adminMenu";
import * as utils from "@/utils/comm";
import container from "@/router/container";

Vue.use(Router);

// window.onbeforeunload = onbeforeunload_handler
//    function onbeforeunload_handler(){
//        var warning="确认退出1111111?"
//        console.log(11111111111111111)
//        return warning
// }

const router = new Router({
  mode: "history",
  routes: [{
    path: "/",
    redirect: "/index"
  }, {
    path: "/index",
    name: "首页",
    component: () =>
      import("@/views/index/index")
  },
  ...container
  ]
});
/* eslint-disable */
let titleTpl = " | 后台管理"

router.beforeEach((to, from, next) => {
  NProgress.start();
  const breadCrumbArray = [];
  const bcObj = {};
  const bcLists = utils.checkMenuToBreadCrumb(adminMenu, to.path, breadCrumbArray, bcObj);
  store.commit("SET_BREADCRUMB_LIST", bcLists.breadCrumbList);
  const checkMenu = bcLists.breadCrumbList.slice(bcLists.breadCrumbList.length - 1, bcLists.breadCrumbList.length)[0];

  if (checkMenu !== undefined) {
    store.commit("ADD_TABS_VIEWS", checkMenu);
    store.commit("TAB_ACTIVE_NAME", checkMenu.path);
  } else {
    store.commit("TABS_VIEWS", []);
    store.commit("TAB_ACTIVE_NAME", "");
  }
  if (to.path === "/login") {
    document.title = `登录${titleTpl}`;
  } else if (to.path === "/401") {
    document.title = `401${titleTpl}`;
  } else if (to.path === "/404") {
    document.title = `404${titleTpl}`;
  } else {
    document.title = `${to.name}${titleTpl}`;
  }
  const role = localStorage.getItem("role");
  const urole = to.meta && to.meta.role;
  if ((role && (role === urole)) || (to.path === "/login") || !urole) {
    next();
  } else {
    alert("没有权限");
    next(false);
  }
});

router.afterEach((to, from) => {
  NProgress.done();
});

export default router;
